package com.classes;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.mbbmap.app.manager.ConfigManager;
import com.mbbmap.app.manager.DBConnectionManager;

public class MatchTraceSplitFile {
	public static final String CONFIG_FILE = "/match_trace.properties";
	public static final java.util.Properties appConfig = new java.util.Properties();
	public static String inputPath;
	public static String outputPatch;
	public static String splitKey;
	public static String donePath;
	public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
	public static String fileOutName;

	public MatchTraceSplitFile() {
		try {
			InputStream configStream = this.getClass().getResourceAsStream(CONFIG_FILE);
			if (configStream != null) {
				appConfig.load(configStream);
			} else {
				throw new Exception("config stream is null");
			}
		} catch (Exception e) {
			System.err.print("can not load file " + CONFIG_FILE);
			e.printStackTrace();
		}
		inputPath = appConfig.getProperty("input.path");
		donePath = appConfig.getProperty("done.path");
		outputPatch = appConfig.getProperty("output.path");
		splitKey = appConfig.getProperty("split.key");
		fileOutName = appConfig.getProperty("file.name");
	}

	public void SplitFile() {
		try {
			File inDir = new File(inputPath);
			if (!inDir.isDirectory()) {
				throw new Exception(inputPath + "is not valid directory path");
			}
			File[] inFile = inDir.listFiles();
			for (int i = 0; i < inFile.length; i++) {
				String strFilePath = inFile[i].getAbsolutePath();
				System.out.println("MatchTraceSplitFile strFilePatch = " + strFilePath);
				if (strFilePath == null) {
					strFilePath = "";
				}
				String strFileName = "";
				if (strFilePath.indexOf(".txt") > 0) {
					strFileName = strFilePath.substring(strFilePath.lastIndexOf("\\") + 1, strFilePath.lastIndexOf("."));
					BufferedReader buffRead = new BufferedReader(new FileReader(strFilePath));
					String tempData;
					String fileName = "";
					String strFolderName = "";
					List<String> lstString = new ArrayList<String>();
					String cusRefNo = "";
					for (tempData = buffRead.readLine(); (tempData != null && tempData != ""); tempData = buffRead.readLine()) {
						strFolderName = outputPatch + "\\" + inFile[i].getName() + "\\";
						File destFolder = new File(strFolderName);
						fileName = outputPatch + "\\" + inFile[i].getName() + "\\"+fileOutName+ cusRefNo + ".txt";
						if (tempData.contains(splitKey)) {
							if (lstString.size() == 0) {
								lstString.add(tempData);
							} else {
								if (!destFolder.exists()) {
									destFolder.mkdir();
								}
								File destFile = new File(fileName);
								if (destFile.exists()) {
									Calendar cal = Calendar.getInstance();
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.DD.HH.mm.ss");
									fileName=outputPatch + "\\" + inFile[i].getName() + "\\"+fileOutName+"_" + cusRefNo + sdf.format(cal.getTime())
											+ ".txt";
									destFile = new File(fileName);
								}
								BufferedWriter bwr = new BufferedWriter(new FileWriter(destFile));
								for (int j = 0; j < lstString.size(); j++) {
									bwr.write(lstString.get(j));
									bwr.write("\n");
								}
								bwr.flush();
								bwr.close();
								lstString.clear();
								lstString.add(tempData);
								insertToCaseDoc(fileName, "text/plain", cusRefNo);
							}
						} else {
							if (tempData.contains("TRANSACTION REFERENCE NBR")) {
								cusRefNo = tempData.substring(tempData.lastIndexOf(":") + 1);
								System.out.println(cusRefNo);
							}
							lstString.add(tempData);
						}
					}
					if (lstString.size() > 0) {
						File destFolder = new File(strFolderName);
						if (!destFolder.exists()) {
							destFolder.mkdir();
						}
						File destFile = new File(fileName);
						if (destFile.exists()) {
							Calendar cal = Calendar.getInstance();
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.DD.HH.mm.ss");
							fileName=outputPatch + "\\" + inFile[i].getName() + "\\"+fileOutName+"_" + cusRefNo + sdf.format(cal.getTime())
									+ ".txt";
							destFile = new File(fileName);						}
						BufferedWriter bwr = new BufferedWriter(new FileWriter(destFile));
						for (int j = 0; j < lstString.size(); j++) {
							bwr.write(lstString.get(j));
							bwr.write("\n");
						}
						bwr.flush();
						bwr.close();
						lstString.clear();
						lstString.add(tempData);
						insertToCaseDoc(fileName, "text/plain", cusRefNo);
					}
					buffRead.close();
					MoveFile(inputPath, inFile[i].getName(), donePath);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void insertToCaseDoc(String file_name, String file_type, String ref_no) {
		
        String connectionPool = ConfigManager.getInstance().getConnectionPool();
        DBConnectionManager connMgr = DBConnectionManager.getInstance();
        Connection conn = connMgr.getConnection(connectionPool, 10000);
        
		try {
			String sql = "insert into casedoc(cd_case_id, cd_name, cd_data, cd_type, cd_length, cd_ref_no, cd_created_by, cd_created_date) "
					+ "values(?, ?, ?, ?, ?, ?, ?, sysdate)";

			PreparedStatement statement = conn.prepareStatement(sql);
			try {
				File blobFile = new File(file_name);
				InputStream in = new FileInputStream(blobFile);
				statement.setString(1, "");
				statement.setString(2, file_name);
				statement.setBinaryStream(3, in, (int) blobFile.length());
				statement.setString(4, file_type);
				statement.setLong(5, blobFile.length());
				statement.setString(6, ref_no.length() > 0 ? ref_no : null);
				statement.setString(7, "System");
				statement.execute();
				System.out.println("inserted to db");
			} finally {
				statement.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connMgr.freeConnection(connectionPool, conn);
		}
	}

	public void MoveFile(String fileDir, String file, String Destination) {
		Calendar cal = Calendar.getInstance();
		String FileName = file;
		File a;
		a = new File(fileDir + "\\" + file);
		String tempDate = dateFormatter.format(cal.getTime()).toString();
		String strTempFolder = Destination + "\\" + tempDate + "\\";
		File DestiFolder = new File(strTempFolder);
		if (DestiFolder.exists() == true) {
			boolean i = a.renameTo(new File(strTempFolder + FileName));
			System.out.println("Move Sucessful " + strTempFolder + FileName + i);
		} else {
			boolean j = DestiFolder.mkdirs();
			System.out.println("make dir Successful " + j);
			boolean i = a.renameTo(new File(strTempFolder + FileName));
			System.out.println("Move Sucessful " + i);
		}
	}

	public static void main(String[] args) {
		MatchTraceSplitFile mtsplit = new MatchTraceSplitFile();
		mtsplit.SplitFile();
	}
}
